#include "room.hpp"
#include "user/user.hpp"
#include "my_server.hpp"
#include "utils/array_utils.hpp"
#include "logger.hpp"

using namespace eiennet;
using namespace std;
using namespace winux;

Room::Room(MyServer *server)
    : server(server)
{
}
winux::Mixed Room::getInfo()
{
    TRACE("winux::Mixed Room::getInfo() {0}, {1}", userList.size(), bubbleList.size())
    winux::Mixed info;
    info.createCollection();
    info["user_list"].createArray();
    for (auto user : userList)
    {
        info["user_list"].add(user->getInfo());
    }

    //后10条记录
    info["bubble_list"].createArray();
    for (auto riter = bubbleList.rbegin(); riter != bubbleList.rend(); riter++)
    {
        info["bubble_list"].add((*riter)->getInfo());
    }

    ReverseMixedArray(info["bubble_list"]);
    return info;
}

void Room::addUser(User *user)
{
    Broad::addUser(user);
    user->room = this;
}

void Room::delUser(uint uid)
{
    TRACE("Room::delUser(uint uid), uid:{0}", uid);
    // userList.lock();
    // for (auto user : userList)
    // {
    //     if (user->uid == uid)
    //     {
    //         user->room = nullptr;
    //         userList.remove(user);
    //         break;
    //     }
    // }
    // userList.unlock();
    for (auto iter = userList.begin(); iter != userList.end(); iter++)
    {
        if ((*iter)->uid == uid)
        {
            userList.erase(iter);
            break;
        }
    }

    TRACE("Room::delUser(uint uid), count:{0}", userList.size());
}
void Room::clearUser()
{
    for (auto user : userList)
    {
        user->room = nullptr;
    }
    Broad::clearUser();
}